﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Handlers;
using System.Web.Mvc;
using System.Web.Routing;
using System.IO;

namespace ComLib.Mvc.Lib.Handlers
{
    public class ImageHandler : IHttpHandler
    {
        /// <summary>
        /// Path of the image folder.
        /// </summary>
        public string ImageFolderPath { get; set; }


        /// <summary>
        /// Name of the domain.
        /// </summary>
        public string DomainName { get; set; }
        
        
        /// <summary>
        /// Initialize.
        /// </summary>
        /// <param name="context"></param>
        public ImageHandler(RequestContext context)
        {
            ProcessRequest(context);
        }


        public bool IsReusable
        {
            get { return false; }
        }
        

        private static void ProcessRequest(RequestContext ctx)
        {
            var response = ctx.HttpContext.Response;
            var request = ctx.HttpContext.Request;
            var server = ctx.HttpContext.Server;
            var file = ctx.RouteData.Values["filename"].ToString();
            const string invalidRequestFile = "thief.gif";
            var path = server.MapPath("~/graphics/");

            response.Clear();
            response.ContentType = GetImageExtension(request.Url.ToString());

            if (string.IsNullOrEmpty(request.ServerVariables["HTTP_REFERER"]))
            {
                response.TransmitFile(path + invalidRequestFile);
            }
            if (request.ServerVariables["HTTP_REFERER"] != null &&
                request.ServerVariables["HTTP_REFERER"].Contains("mikesdotnetting.com"))
            {
                response.TransmitFile(path + file);
            }
            else
            {
                response.TransmitFile(path + invalidRequestFile);
            }
            response.End();
        }



        private static string GetImageExtension(string url)
        {
            switch (Path.GetExtension(url))
            {
                case ".gif":
                    return "Image/gif";
                case ".jpeg":
                    return "Image/jpeg";
                case ".jpg":
                    return "Image/jpeg";
                case ".png":
                    return "Image/png";
                default:
                    break;
            }
            return null;
        }


        private void Init()
        {
            ImageFolderPath = "~/content/images/";
            DomainName = "knowledgedrink";
        }

        #region IHttpHandler Members


        public void ProcessRequest(HttpContext context)
        {
            throw new NotImplementedException();
        }

        #endregion
    }
}
